package com.myidis.servlet;


import java.util.List;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.myidis.entity.RightPermission;
import com.myidis.entity.RightRolePermission;
import com.myidis.mapper.RightPermissionMapper;
import com.myidis.mapper.RightRolePermissionMapper;
import com.myidis.request.PermissionReq;
import com.myidis.response.PermissionRes;

@Service
public class RightRolePermissionServlet {
	@Autowired
	private RightPermissionMapper rightPermissionMapper;
	@Autowired
	private RightRolePermissionMapper rightRolePermissionMapper;
	
	public List<PermissionRes> getByRole(int id) {
		int i = 0;
		List<RightPermission> list = rightPermissionMapper.all();
		List<RightRolePermission> rights = rightRolePermissionMapper.getByRole(id);
		List<PermissionRes> res = new ArrayList<PermissionRes>();
		for(RightRolePermission right: rights) {
			while(right.getPid() != list.get(i).getId()) {
				res.add(new PermissionRes(list.get(i++), false));
			}
			res.add(new PermissionRes(right.getId(), list.get(i++), true));
		}
		for(int j = i; j < list.size(); j++)
			res.add(new PermissionRes(list.get(j), false));
		
		return res;
	}
	
	public int right(int id, List<PermissionReq> req) {
		for(PermissionReq right: req) {
			if(right.isStatus()) {
				if(right.getId() == -1) {
					RightRolePermission temp = new RightRolePermission();
					temp.setRid(id);
					temp.setPid(right.getPid());
					rightRolePermissionMapper.insert(temp);
				}
			}
			else {
				if(right.getId() != -1)
					rightRolePermissionMapper.delete(right.getId());
			}
		}
		return 1;
	}
	
	public List<RightRolePermission> getByRoles(int id) {
		return rightRolePermissionMapper.getByRole(id);
	}
	
	public RightRolePermission getOne(int id) {
		return rightRolePermissionMapper.getOne(id);
	}
	
	public int insert(List<RightRolePermission> objs) {
		int count = 0;
		for (RightRolePermission obj: objs) {
			System.out.println(obj.toString());
			count += rightRolePermissionMapper.insert(obj);
		}
		return count;
	}
	
	public int update(int id, RightRolePermission obj) {
		obj.setId(id);
		return rightRolePermissionMapper.update(obj);
	}
	
	public int delete(int[] ids) {
		int count = 0;
		for(int i = 0; i < ids.length; i++)
			count += rightRolePermissionMapper.delete(ids[i]);
		return count;
	}
}
